//
//  Nanny.m
//  kvo-oc
//
//  Created by 看着太阳吃烧饼 on 15/5/16.
//  Copyright (c) 2015年 看着太阳吃烧饼. All rights reserved.
//

#import "Nanny.h"
#import "Child.h"
@implementation Nanny

- (id)initWithChild:(Child *)child {
    if (self = [super init]) {
        _child = child;
        [_child addObserver:self forKeyPath:@"cleanValue" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
        [_child addObserver:self forKeyPath:@"happyValue" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
    }
    return self;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:@"cleanValue"]) {
        NSNumber *cleanNumber = change[@"new"];
        if ([cleanNumber integerValue] < 5) {
            NSLog(@"洗澡");
            Child *child = (Child *)object;
            child.cleanValue = 10;
        }
    }
    if ([keyPath isEqualToString:@"happyValue"]) {
        NSNumber *happyNumber = change[@"new"];
        if ([happyNumber integerValue] <6) {
            NSLog(@"玩耍");
            Child *child = (Child *)object;
            child.happyValue = 10;
        }
    }
}

- (void)dealloc {
    [_child removeObserver:self forKeyPath:@"cleanValue"];
    [_child removeObserver:self forKeyPath:@"happyValue"];
}
@end
